package com.luis.toolsuite.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.luis.toolsuite.downsampling.model.DataPoint;
import com.luis.toolsuite.downsampling.service.DownsampleStrategy;
import com.luis.toolsuite.service.DataRepository;
import com.luis.toolsuite.util.Helper;


@Controller
public class DownsampleController {
	
	@Autowired
	private Map<String,DownsampleStrategy> strategyMap;
	@Autowired
	private DataRepository dataService;
	
	
	@RequestMapping("/data")
	@ResponseBody
	public Map<String,List<Object[]>> data() {
		//异常诊断模型数据
		final int relId = 532;
		Pageable pageable = PageRequest.of(1,Helper.TOTAL_SIZE);
		Iterable<DataPoint> dataList = dataService.findByRelId(relId,pageable);
		prepareDataSet(dataList);
		List<DataPoint> dataset= StreamSupport.stream(dataList.spliterator(), false).sorted(Comparator.comparing(DataPoint::getTime)).collect(Collectors.toList());
		
		Map<String,List<Object[]>> resultMap = new LinkedHashMap<>();
		
		resultMap.put("原始数据", prepareResult(dataset));
		strategyMap.forEach((k,v)->{
			List<DataPoint> result = v.downsample(dataset);
			resultMap.put(k, prepareResult(result));
		});
		
		
		return resultMap;
	}
	
	private void prepareDataSet(Iterable<DataPoint> dataset) {
		Iterator<DataPoint> i = dataset.iterator();
		while(i.hasNext()) {
			DataPoint p = i.next();
			if(p.getValue2() != null) {
				p.setScore(BigDecimal.valueOf(p.getValue()).add(BigDecimal.valueOf(p.getValue2())).doubleValue());
			}else{
				p.setScore(BigDecimal.valueOf(p.getValue()).doubleValue());
			}
			
		}
	}
	
	private List<Object[]> prepareResult(List<DataPoint> downList){
		for(DataPoint p : downList){
			if(p.getTime() == null || p.getScore() == null)
				System.out.println(p.getTime());
		}
		return downList.stream().map(p->new Object[] {p.getTime(),p.getScore()}).collect(Collectors.toList());
	}
}
